

import { Dropdown, DropdownProps } from 'antd';
import './forms.scss';
import { useFormItemInit } from './hooks';
import { FormItemBaseProps } from './interface';
import React from 'react';
import { Components } from '../..';




interface IProps extends FormItemBaseProps {
    children?: React.ReactNode,
}
export default function MyDropdown(props: IProps) {
    const { formControl, className = '', children, style={} } = props;
    const {
        value, setValue,
        readonly,
        outerClassName,
        layout,
        outerStyle,
        labelStyle,
        options,
    } = useFormItemInit(formControl, className, style);

    const [selectedKeys, setSelectedKeys] = React.useState<string[]>([value]);

    const [items, setItems] = React.useState<any[]>([]);

    const [displayValue, setDisplayValue] = React.useState(value);

    React.useEffect(() => {
        if (options?.length) {
            const option = options.find((v:any) => v.value === value);
            if (option) {
                setDisplayValue(option.label);
            }
        }
    }, [value]);
    React.useEffect(() => {
        const tpmItems: any[] = [];
        options.forEach((o:any) => {
            tpmItems.push({ key: o.value, label: o.label, disabled: o.disabled });
        });
        
        setItems([...tpmItems]);
    }, [options]);

    const onClick = (info: { key: string }) => {
        setValue(info.key);
        formControl.setValue(info.key, 'user');
        setSelectedKeys([info.key]);
    };

    const dropdownProps: DropdownProps = {
        className: 'select',
        disabled: readonly,
        menu: {
            selectedKeys,
            items,
            onClick,
        },
    };

    return (
        <div component-name='form-item' className={outerClassName} style={outerStyle}>
            <div className={`field ${layout}`}>
                <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                <div className='control'>
                    <div className="value">
                        {
                            readonly ?
                                <div className='readonly'>{displayValue}</div> :
                                <Dropdown {...dropdownProps} trigger={['click']} children={children} />
                        }
                    </div>
                </div>
            </div>

        </div>
    )
}
